<script setup lang="ts">
import { orderState, orderStateActions, orderStateList, pageUrl } from '@/utils/constants'
import { deleteOrderApi, getOrderDetailByIdApi, putOrderCancelByIdApi } from '@/api/order'
import type { orderResult } from '@/types/order'
import { ref, computed } from 'vue'
import { fullUrl, getPayPageUrl, formatPrice, onShowRefreshData } from '@/utils/common'
import receiveButton from '@/pagesOrder/components/receiveButton.vue'
import cancelButton from '@/pagesOrder/components/cancelButton.vue'
import { safeBottom } from '@/utils/constants'
import { createStripePaymentIntentApi, type StripeApiResponse, createPaymentApi } from '@/api/stripe'

//订单详情
const detailData = ref<orderResult>()
const getDetailData = async () => {
  const res = await getOrderDetailByIdApi(orderId)
  detailData.value = res.result
}


// 复制内容
const onCopy = () => {
  // 设置系统剪贴板的内容
  uni.setClipboardData({ data: detailData.value!.order_no })
}
// 获取页面参数
const query = defineProps<{
  id: string
}>()

//订单ID
const orderId = Number(query.id)

//倒计时结束事件
const onTimeUp = () => {
  if (detailData.value?.status != orderState.canceled) {
    putOrderCancelByIdApi({
      id: detailData.value!.id,
      time_out: true,
    })
  }
  detailData.value!.status = orderState.canceled
}

let isFeightVal = ref(true);
const sharePopupRef = ref()
const onPay = async () => {
  const currentOrderId = String(orderId);
  const apiResponseDirectly = await createPaymentApi({
    pay_way: 'balance',
    id: currentOrderId
  })

  if(apiResponseDirectly.code === 200){
    uni.showToast({
      title: 'Payment Success',
      icon: 'none'
    });
    setTimeout(() => {
      uni.redirectTo({ url: `${pageUrl['order-list']}` })
    }, 800)
  }

   console.log(apiResponseDirectly, "阿琴的数据")

   return;
  // sharePopupRef.value?.open()
  //判断如果是网页h5环境，则提示请前往app支付
  // #ifdef H5
  uni.showModal({
    title: 'Payment Notice',
    content: 'Please use our mobile app for a better payment experience.',
    showCancel: false,
    confirmText: 'OK'
  });
  // #endif


  // #ifdef APP-PLUS
  if (!detailData.value) {
    console.error("Order details not available for payment preparation.");
    uni.showToast({ title: 'Order details not available', icon: 'none' });
    return;
  }

  try {
    // Call your new API to get payment intent
    // Runtime error "No result object" suggests that 'createStripePaymentIntentApi'
    // returns StripeApiResponse directly, not wrapped in a '.result' property.

    if (!detailData.value || !detailData.value.detail || detailData.value.detail.length === 0) {
      console.error("Order details or product details not available for payment preparation.");
      uni.showToast({ title: 'Order/Product details not available', icon: 'none' });
      return;
    }

    // Calculate total price from items in detailData.value.detail
    let itemsTotalPrice = 0;
    for (const item of detailData.value.detail) {
      itemsTotalPrice += Number(item.price) * Number(item.num);
    }

    // Subtract coupon discount
    // Assuming detailData.value.discount_data.coupon_discount is a positive number representing the discount amount
    const couponDiscount = Number(detailData.value.discount_data?.coupon_discount || 0);
    const finalAmountToPay = itemsTotalPrice - couponDiscount;

    if (finalAmountToPay < 0) {
      console.error("Final amount to pay is negative after discount:", finalAmountToPay);
      uni.showToast({ title: 'Error in calculating amount', icon: 'none' });
      return;
    }

    const currency = 'USD'; // Assuming USD, please confirm or change
    // Convert final calculated amount to cents
    const amountInCents = String(finalAmountToPay);
    const currentOrderId = String(orderId);

    console.log('[Debug] Preparing payment intent with (calculated based on items):', {
      currency: currency,
      amount: amountInCents,
      order_id: currentOrderId,
      items_total_price_before_discount: itemsTotalPrice,
      coupon_discount_applied: couponDiscount,
      final_amount_to_pay_before_cents_conversion: finalAmountToPay,
      original_order_pay_price: detailData.value.pay_price // For comparison/debugging
    });

    // 暂时先用余额支付 （app过审）
    // const apiResponseDirectly = await createPaymentApi({
    //   pay_way: 'balance',
    //   id: currentOrderId
    // })
    // console.log(apiResponseDirectly, "阿琴的数据")

    // TODO: 暂时注释掉，后期需要换回来 （卡支付）
    // const apiResponseDirectly = await createStripePaymentIntentApi({
    //   currency: currency,
    //   amount: amountInCents,
    //   order_id: currentOrderId,
    // });

    // Log the direct response to see its structure.
    // This is what we believe IS the StripeApiResponse.
    console.log("Direct API Response from createStripePaymentIntentApi:", JSON.stringify(apiResponseDirectly));

    // Now, we assert that apiResponseDirectly IS the StripeApiResponse.
    // If the linter complains here that apiResponseDirectly (e.g. if typed as Data<StripeApiResponse>)
    // doesn't have .code, .data, it means the type definition of createStripePaymentIntentApi
    // or the underlying 'request' utility is inconsistent with runtime behavior.
    // Forcing the type for now to align with runtime evidence.
    const stripeApiActualResponse = apiResponseDirectly as unknown as StripeApiResponse;


    // Check for successful API response
    const isResponseValid = stripeApiActualResponse &&
      stripeApiActualResponse.code === 200 &&
      stripeApiActualResponse.data;

    if (!isResponseValid) {
      let errorMsg = 'Failed to create payment intent';
      if (!stripeApiActualResponse) {
        errorMsg += ' (API response is null, undefined, or not a valid StripeApiResponse structure after casting)';
        console.error("Failed Payment Intent: API response is problematic:", JSON.stringify(apiResponseDirectly));
      } else if (stripeApiActualResponse.code !== 200) {
        errorMsg += ` (API Code: ${stripeApiActualResponse.code}, Sent Amount: ${amountInCents} cents, Msg: ${stripeApiActualResponse.msg || 'N/A'})`;
        console.error("Failed Payment Intent: Invalid code:", JSON.stringify(stripeApiActualResponse), "Sent amount in cents:", amountInCents);
      } else if (!stripeApiActualResponse.data) {
        errorMsg += ' (Missing data field)';
        console.error("Failed Payment Intent: Missing data field:", JSON.stringify(stripeApiActualResponse));
      } else {
        errorMsg += ' (Unknown structure issue after basic checks)';
        console.error("Failed Payment Intent: Unknown structure issue:", JSON.stringify(stripeApiActualResponse));
      }

      uni.showToast({ title: errorMsg, icon: 'none', duration: 5000 });
      return;
    }



    const paymentData = stripeApiActualResponse.data; // Access data from the actual response

    const orderInfo = {
      "customer": paymentData.customer,
      "ephemeralKey": paymentData.ephemeralKey,
      "isAllowDelay": true,
      "merchantName": "DCloud",
      "paymentIntent": paymentData.paymentIntent,
      "publishKey": paymentData.publishableKey, // Mapped from publishableKey
      "billingDetails": {
        "name": detailData.value.address?.name || "",
        "email": "", // Add email if available, e.g., detailData.value.user_email
        "phone": detailData.value.address?.phone || "",
        "address": {
          "city": "", // Was detailData.value.address?.city_name - property does not exist
          "country": detailData.value.address?.country_code || "US", // Use country_code from address, or default to 'US'
          "line1": detailData.value.address?.full_address || "", // Was detailData.value.address?.address - property does not exist, using full_address
          "line2": "",
          "postalCode": "", // Was detailData.value.address?.postal_code - property does not exist
          "state": "" // Was detailData.value.address?.province_name - property does not exist
        }
      }
    };

    //获取支付渠道 和 发起支付 (仅在 App 环境下执行)
    // #ifdef APP-PLUS
    plus.payment.getChannels(function (channels: any[]) { // Added type for channels
      let stripeSev: any = null; // Initialize stripeSev with null and specific type
      for (var i in channels) {
        var channel = channels[i];
        if (channel.id === 'stripe') {
          stripeSev = channel;
          break; // Found stripe, no need to continue loop
        }
      }

      if (!stripeSev) {
        console.error("Stripe payment channel not found.");
        uni.showToast({ title: 'Stripe payment channel not found', icon: 'none' });
        return;
      }

      //发起支付
      plus.payment.request(stripeSev, orderInfo, function (result: { rawdata?: string }) { // Added type for result
        if (result.rawdata) {
          const rawdata = JSON.parse(result.rawdata);
          console.log("支付成功", rawdata);
          // Optionally, navigate to a success page or refresh order details
          uni.showToast({ title: 'Payment Successful', icon: 'success' });
          getDetailData(); // Refresh order details
        } else {
          console.error("Payment successful but no rawdata received:", result);
          uni.showToast({ title: 'Payment issue: No data', icon: 'none' });
        }
      }, function (e: any) { // Added type for e
        console.log("支付失败：" + JSON.stringify(e));
        //  uni.showToast({ title: 'Payment Failed: ' + (e.message || JSON.stringify(e)), icon: 'none' });
      });
    }, function (e: any) { // Added type for e
      console.log("获取支付渠道失败：" + JSON.stringify(e));
      uni.showToast({ title: 'Failed to get payment channels', icon: 'none' });
    });
    // #endif

    // #ifndef APP-PLUS
    console.warn('Payment via plus.payment is only available in APP environment.');
    uni.showToast({ title: 'Payment not supported in this environment', icon: 'none' });
    // #endif

  } catch (error: any) {
    console.error("Error in onPay:", error);
    uni.showToast({ title: 'Error during payment: ' + (error.message || 'Unknown error'), icon: 'none' });
  }
  // #endif

}

//删除订单
const onDeleteOrder = () => {
  uni.showModal({
    title: 'Tips',
    content: 'Are you sure to delete the order?',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        await deleteOrderApi({
          id: [orderId],
        })
        uni.showToast({
          title: 'Deletion successful',
          icon: 'success',
          mask: true,
        })
        setTimeout(() => {
          uni.redirectTo({ url: `${pageUrl['order-list']}` })
        }, 500)
      }
    },
  })
}

onShowRefreshData(() => {
  getDetailData()
}, true)

const showDelivery = computed(() => {
  return (
    [orderState.toReceived, orderState.toEvaluate, orderState.completed].includes(
      detailData.value!.status,
    ) && detailData.value!.delivery.length > 0
  )
})

const onCancel = () => {
  if (detailData.value?.pay_time) {
    detailData.value!.status = orderState.applyCancel
  } else {
    detailData.value!.status = orderState.canceled
  }
}
</script>

<template>
  <scroll-view scroll-y class="viewport" id="scroller">
    <template v-if="detailData">
      <!-- 订单状态 -->
      <view class="overview" :style="{ paddingTop: '30rpx' }">
        <!-- 待付款状态:展示去支付按钮和倒计时 -->
        <template v-if="detailData.status === orderState.toPay">
          <view class="status icon-clock" v-if="orderStateList[detailData.status]">{{
            orderStateList[detailData.status].text }}</view>
          <view class="tips">
            <view class="time">
              <view>Still left</view>
              <uni-countdown :second="detailData.countdown" @timeup.once="onTimeUp" color="#fff" splitor-color="#fff"
                :show-day="false" :show-colon="false" />
              <view>automatic cancellation</view>
            </view>
          </view>
          <view @click="onPay" class="button primary">Pay Now</view>
          <!-- <navigator
            class="button primary"
            :url="getPayPageUrl(orderId, detailData.pay_price)"
            hover-class="none"
          >
          Pay Now
          </navigator> -->
        </template>
        <!-- 其他订单状态:展示再次购买按钮 -->
        <template v-else>
          <!-- 订单状态文字 -->
          <view class="status"> {{ orderStateList[detailData.status].text }} </view>
        </template>
      </view>

      <view class="shipment" v-show="detailData.address">
        <view class="locate">
          <view class="user"> {{ detailData.address.name }} {{ detailData.address.phone }} </view>
          <view class="address">{{ detailData.address.full_address }} </view>
        </view>
        <!-- 配送状态 -->
        <view class="item" v-if="showDelivery">
          <view class="delivery-card">
            <template v-if="detailData.delivery.length > 1">
              <navigator class="delivery" :url="`${pageUrl['order-delivery']}?order_id=${orderId}`" hover-class="none">
                <view v-if="detailData.status == orderState.toReceived" class="delivery-tip">
                  <text>Order split into {{ detailData.delivery.length }} packages for shipment.</text>
                </view>
                <view v-else class="delivery-tip">
                  <text>Order split into multiple packages for shipment</text>
                  <text>{{ detailData.delivery.length }} package has been dispatched</text>
                </view>
                <view class="more">
                  <text class="icon-right"></text>
                </view>
              </navigator>
            </template>
            <template v-else>
              <navigator class="delivery" :url="`${pageUrl['order-delivery']}?order_id=${orderId}`" hover-class="none"
                v-for="(item, idx) in detailData.delivery" :key="idx">
                <view class="delivery-info">
                  <view class="info-item">
                    <view class="item-label">Logistics company</view>
                    <view class="item-content">
                      {{ item.delivery_company?.name || 'No need for logistics' }}
                    </view>
                  </view>
                  <view class="info-item">
                    <view class="item-label">Logistics tracking number</view>
                    <view class="item-content">{{ item.delivery_no || '' }}</view>
                  </view>
                </view>
                <view class="more">
                  <text class="icon-right"></text>
                </view>
              </navigator>
            </template>
          </view>
        </view>
      </view>

      <!-- 商品信息 -->
      <view class="goods" v-if="detailData.detail.length > 0">
        <view class="item" v-for="detail in detailData.detail" :key="detail.id">
          <navigator class="navigator" :url="`${pageUrl['goods-detail']}?id=${detail.goods_id}`" hover-class="none">
            <view>
              <image class="cover" :src="fullUrl(detail.image)"></image>
            </view>
            <view class="meta">
              <view class="name ellipsis">{{ detail.goods_name }}</view>
              <!-- <view class="type">{{ detail.spec_text.split('，')[1] }}</view> -->
              <view class="meta-spec" v-if="detail.spec_text">
                <view class="color">
                  <text>Color：</text>
                  <image class="color" :src="fullUrl(detail.spec_text.split('，')[0])" alt="" />
                </view>
                <view class="size">
                  <text>Size：</text>{{ detail.spec_text.split('，')[1] }}
                </view>
              </view>
              <view class="price">
                <view class="actual">
                  <text class="symbol">$</text>
                  <text>{{ detail.price }}</text>
                </view>
              </view>
              <view class="quantity">x{{ detail.num }}</view>
            </view>
          </navigator>

          <view class="operate">
            <view v-if="
              orderStateActions.evaluatable.includes(detailData.status) &&
              detail.evaluate_time <= 0
            ">
              <navigator :url="`${pageUrl['order-evaluate']}?detail_id=${detail.id}`" open-type="navigate"
                hover-class="navigator-hover" class="button">
                Go evaluate
              </navigator>
            </view>

            <view v-if="detail.apply_refund">
              <navigator :url="`${pageUrl['order-refund']}?order_id=${detailData.id
                }&detail_data=${JSON.stringify(detail)}`" open-type="navigate" hover-class="navigator-hover"
                class="button">
                Start a return
              </navigator>
            </view>
          </view>
        </view>
      </view>

      <view class="goods">
        <view class="total">
          <view class="row">
            <view class="text">Total Price</view>
            <view class="symbol">{{ formatPrice(detailData.total_price) }}</view>
          </view>
          <view class="row">
            <view class="text">Shipping Fee</view>
            <view class="symbol">{{ formatPrice(detailData.freight) }}</view>
          </view>
          <view class="row">
            <view class="text">Discount</view>
            <view class="symbol discount">
              {{ formatPrice(detailData.discount_data.coupon_discount) }}
            </view>
          </view>
          <view class="row">
            <view class="text">Amount Due</view>
            <view class="symbol">{{ formatPrice(detailData.pay_price) }}</view>
          </view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="detail">
        <view class="row">
          <view class="item">
            <view class="item-title">Order No.</view>
            <view>
              {{ detailData.order_no }}
              <text class="copy" @tap="onCopy">Copy</text>
            </view>
          </view>
          <view class="item">
            <view class="item-title">Order Time</view>
            <view>{{ detailData.create_time }}</view>
          </view>
          <view class="item" v-if="detailData.pay_time">
            <view class="item-title">Payment Time</view>
            <view>{{ detailData.pay_time }}</view>
          </view>
          <view class="item">
            <view class="item-title">Buyer Note</view>
            <view style="width: 80%">{{ detailData.remark || '--' }}</view>
          </view>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class="toolbar-height" :style="safeBottom"></view>
      <view class="toolbar" :style="safeBottom">
        <!-- 待付款状态:展示支付按钮 -->
        <template v-if="detailData.status === orderState.toPay">
          <cancelButton :status="detailData.status" :id="detailData.id" className="button secondary"
            @cancel="onCancel" />
          <view @click="onPay" class="button primary">
            Pay Now
          </view>
          <!-- <navigator
            class="button primary"
            :url="getPayPageUrl(detailData.id, detailData.pay_price)"
            hover-class="none"
          >
          Pay Now
          </navigator> -->
        </template>
        <!-- 其他订单状态:按需展示按钮 -->
        <template v-else>
          <view v-if="orderStateActions.deletable.includes(detailData.status)">
            <view class="button secondary" @tap="onDeleteOrder"> Delete Order </view>
          </view>

          <cancelButton :status="detailData.status" :id="detailData.id" className="button secondary"
            @cancel="onCancel" />

          <receiveButton :status="detailData.status" :id="detailData.id" :payment-trade-info="detailData.payment_trade"
            className="button secondary" />

          <view v-if="orderStateActions.evaluatable.includes(detailData.status)">
            <navigator :url="`${pageUrl['order-evaluate']}?order_id=${orderId}`" class="button secondary"
              hover-class="none">
              One-click Review
            </navigator>
          </view>

          <navigator class="button primary" :url="`${pageUrl['order-create']}?orderId=${orderId}`" hover-class="none">
            Buy Again
          </navigator>
        </template>
      </view>
    </template>
  </scroll-view>

  <uni-popup ref="sharePopupRef" type="bottom" background-color="#fff">
    <view class="rule-item">
      <view class="confirm-btn">
        <navigator :url="getPayPageUrl(detailData.id, detailData.pay_price)" hover-class="none">confirm</navigator>
      </view>
      <view class="rule-content">

        <view class="rule-title">
          <radio value="standard" :checked="isFeightVal" color="#000000" />
          <text>Credit/Debit Card</text>
        </view>
        <view class="desc">
          <image src="/static/icons/payment_xyk-CLFe9UE9.svg" mode="scaleToFill"
            style="width: 100rpx; height: 50rpx;" />
        </view>
      </view>
    </view>
  </uni-popup>
</template>

<style lang="scss" scoped>
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.rule-item {
  // display: flex;
  // align-items: center;
  padding: 10rpx 30rpx 30rpx 30rpx;

  .confirm-btn {
    width: 100%;
    text-align: right;
    margin-bottom: 30rpx;
    font-size: 26rpx;
    font-weight: bold;
  }

  .rule-content {
    display: flex;
    justify-content: space-between;
    flex: 1;
    align-items: center;
    margin-left: 20rpx;
  }

  .rule-title {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    margin-bottom: 10rpx;

    radio {
      margin-right: 8rpx;
    }
  }

  .desc {
    font-size: 26rpx;
    color: #999;

    image {
      position: relative;
      right: -14rpx;
    }
  }
}

.card {
  display: flex;
  flex-direction: column;
  line-height: 1.6;
  padding: 20rpx;
  margin: 20rpx;
  border-radius: 30rpx;
  background-color: #fff;
}

.navbar {
  width: 750rpx;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9;
  /* background-color: #f8f8f8; */
  background-color: transparent;

  .wrap {
    position: relative;

    .title {
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      /* color: #000; */
      color: transparent;
    }

    .back {
      position: absolute;
      left: 0;
      height: 44px;
      width: 44px;
      font-size: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      /* color: #000; */
      color: #fff;
    }
  }
}

.viewport {
  background-color: #f7f7f8;
}

.overview {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 35rpx;
  color: #fff;
  background-image: url('~@/static/images/bg.png');
  background-size: cover;

  .status {
    font-size: 36rpx;
  }

  .status::before {
    margin-right: 6rpx;
    font-weight: 500;
  }

  .tips {
    margin: 30rpx 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    align-items: center;

    .money {
      margin-right: 30rpx;
    }

    .time {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;
      padding-top: 10rpx;
    }
  }

  .button-group {
    margin-top: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .button {
    width: 260rpx;
    height: 64rpx;
    margin: 0 10rpx;
    text-align: center;
    line-height: 64rpx;
    font-size: 28rpx;
    color: #ff5f3c;
    border-radius: 68rpx;
    background-color: #fff;
    display: inline-block;
  }
}

.shipment {
  line-height: 1.4;
  padding: 0 20rpx;
  margin: 20rpx 20rpx 20rpx;
  border-radius: 30rpx;
  background-color: #fff;

  .locate,
  .item {
    // min-height: 120rpx;
    padding: 30rpx 30rpx 25rpx 75rpx;
    background-size: 50rpx;
    background-repeat: no-repeat;
    background-position: 6rpx center;
  }

  .locate {
    background-image: url('~@/static/images/locate.png');
    border-bottom: 1rpx solid #eee;

    .user {
      font-size: 26rpx;
      color: #444;
    }

    .address {
      font-size: 24rpx;
      color: #666;
    }
  }

  .item {
    background-image: url('~@/static/images/car.png');
    border-bottom: 1rpx solid #eee;
    position: relative;

    .message {
      font-size: 26rpx;
      color: #444;
    }

    .date {
      font-size: 24rpx;
      color: #666;
    }
  }

  .delivery {
    display: flex;
    align-items: center;

    .delivery-tip {
      font-size: 24rpx;
      display: flex;
      flex-direction: column;
    }

    .info-item {
      display: flex;
      font-size: 24rpx;
      padding-bottom: 10rpx;
    }

    .item-label {
      color: #999999;
      margin-right: 20rpx;
    }

    .item-content {
      font-size: 26rpx;
    }

    .more {
      margin-left: auto;
    }
  }
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 30rpx;
  background-color: #fff;

  .item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;

    .navigator {
      display: flex;
      // margin: 20rpx 0;
    }

    .cover {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      position: relative;
    }

    .name {
      font-size: 26rpx;
      color: #444;
    }

    .meta-spec {
      background: transparent;
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #888;

      span {
        font-size: 24rpx;
        color: #888;
      }

      .color {
        margin-right: 10rpx;

        image {
          width: 60rpx;
          height: 60rpx;
          border-radius: 50%;
          border: 1px solid #e3e3e3;
        }
      }
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
      max-width: 91%;
    }

    .price {
      display: flex;
      margin-top: 6rpx;
      font-size: 24rpx;
    }

    .symbol {
      font-size: 20rpx;
      position: relative;
      top: -2rpx;
    }

    .original {
      color: #999;
      text-decoration: line-through;
    }

    .actual {
      margin-left: 10rpx;
      color: #444;
    }

    .text {
      font-size: 22rpx;
    }

    .operate {
      display: flex;
      align-items: center;
      flex-direction: row-reverse;

      .button {
        display: flex;
        justify-content: center;
        border-radius: 60rpx;
        height: 50rpx;
        width: 150rpx;
        align-items: center;
        border: 1rpx solid #ccc;
        color: #444;
        font-size: 20rpx;
        margin-left: 20rpx;
      }
    }

    .quantity {
      position: absolute;
      right: 0;
      font-size: 24rpx;
      color: #444;
    }

    .action {
      display: flex;
      flex-direction: row-reverse;
      justify-content: flex-start;
      padding: 30rpx 0 0;

      .button {
        width: 200rpx;
        height: 60rpx;
        text-align: center;
        justify-content: center;
        line-height: 60rpx;
        margin-left: 20rpx;
        border-radius: 60rpx;
        border: 1rpx solid #ccc;
        font-size: 26rpx;
        color: #444;
      }

      .primary {
        color: #ff5f3c;
        border-color: #ff5f3c;
      }
    }
  }

  .total {
    line-height: 1.4;
    font-size: 26rpx;
    padding: 20rpx 0;
    color: #666;

    .row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10rpx 0;
    }

    .symbol::before {
      content: '$';
      font-size: 80%;
      margin-right: 3rpx;
      position: relative;
      top: -2rpx;
    }

    .discount::before {
      content: '- $';
      font-size: 80%;
      margin-right: 3rpx;
      position: relative;
      top: -2rpx;
    }

    .primary {
      color: #cf4444;
      font-size: 36rpx;
    }
  }
}

.detail {
  line-height: 1.4;
  padding: 20rpx;
  margin: 20rpx;
  font-size: 26rpx;
  color: #666;
  border-radius: 30rpx;
  background-color: #fff;

  .title {
    font-size: 30rpx;
    color: #444;
  }

  .row {
    padding: 20rpx 0;

    .item {
      padding: 10rpx 0;
      display: flex;

      .item-title {
        margin-right: 30rpx;
        width: 164rpx;
      }
    }

    .copy {
      border-radius: 20rpx;
      font-size: 20rpx;
      border: 1px solid #ccc;
      padding: 5rpx 20rpx;
      margin-left: 10rpx;
    }
  }
}

.toolbar-height {
  height: 100rpx;
  box-sizing: content-box;
}

.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  flex-direction: row;
  justify-content: flex-end;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;

  .button {
    display: flex;
    justify-content: center;
    align-items: center;

    width: 200rpx;
    height: 60rpx;
    margin-left: 15rpx;
    font-size: 26rpx;
    border-radius: 72rpx;
    // border: 1rpx solid #ccc;
    color: #444;
  }

  .delete {
    order: 4;
  }

  .button {
    order: 3;
  }

  .secondary {
    order: 2;
    background: #fff;
    color: #ff5f3c;
    border-color: #ff5f3c;
  }

  .primary {
    order: 1;
    color: #fff;
    background-color: #ff5f3c;
  }
}
</style>
